﻿using HuaCheng.DataAccess;
using HuaCheng.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using System.Xml;

namespace HuaCheng.Controller
{
    /// <summary>
    /// 通道锁定Control层
    /// </summary>
    public class ChannelLockControl
    {
        public static int row;//数据表中该设备的通道映射的行数
        public static int col;//数据表中该设备的通道映射的列数
        /// <summary>
        /// 获取数据库映射表设备通道信息填充到数据集
        /// </summary>
        /// <param name="ip">设备ip</param>
        /// <returns></returns>
        public static DataSet SqlFillDataSet(string ip, int gid, int mid)
        {
            List<int> data = (List<int>)ChlMapHelper.QueryMapRowAndCol(ip, gid, mid);//查询数据库得数据表行和列
            row = data[1];//行数
            col = data[0];//列数
            DataTable defaultDt;//空表
            DataSet defaultDs;//空数据集
            //创建DataTable对象dt
            defaultDt = new DataTable("chlLockXML");
            ///创建DataSet对象ds
            defaultDs = new DataSet("chlLockXML");
            if (row == 0)//表中没有记录
            {
                row = 0;
                col = 1;
            }
            else
            {
                defaultDt.Columns.Add(new DataColumn("0", typeof(bool)));//有数据才需要check全选

            }
            for (int i = 1; i <= col; i++)//动态添加列
            {
                defaultDt.Columns.Add(new DataColumn(Convert.ToString(i), typeof(string)));
            }
            for (int i = 0; i < row; i++)//动态添加行
            {
                DataRow r = defaultDt.NewRow();
                r[0] = false;
                for (int j = 1; j <= col; j++)
                {
                    r[j] = "0";
                }
                defaultDt.Rows.Add(r);
            }
            defaultDs.Tables.Add(defaultDt);
            return defaultDs;
        }
        /// <summary>
        /// 读取xml通道锁定信息
        /// </summary>
        /// <param name="file"></param>
        /// <param name="ds"></param>
        /// <returns></returns>
        public static DataSet XmlFillDataSet(string file, DataSet ds)
        {
            if (System.IO.File.Exists(file))
            {
                //导入xml文档
                XmlDocument xmlDoc = new XmlDocument();
                DataTable dt = new DataTable();
                dt = ds.Tables[0];
                try
                {
                    xmlDoc.Load(file);//加载xml文件
                    if (xmlDoc.SelectSingleNode("root") != null)//1.如果文件存在且通道不为空
                    {
                        //选择SubDev_Info结点并得到旗下所有子节点
                        XmlNodeList xmlNodeList = xmlDoc.GetElementsByTagName("SubDev_Info");
                        XmlNodeList unitXmlNodeList = xmlNodeList[0].ChildNodes;
                        //填充数据
                        int xrow = 0;
                        int xcol = 0;
                        foreach (XmlNode unitNode in unitXmlNodeList)//每行
                        {
                            int checkAll = 0;
                            XmlNodeList chlNodeList = unitNode.ChildNodes;
                            foreach (XmlNode chlNode in chlNodeList)//每列
                            {
                                xcol++;
                                dt.Rows[xrow][xcol] = chlNode.Attributes["Value"].Value;
                                if (chlNode.Attributes["Value"].Value == "1")
                                    checkAll++;
                                if (xcol == col)//数据表一行排满换行
                                {
                                    dt.Rows[xrow][0] = checkAll == col ? true : false;//如果全为1则第一列为check
                                    xrow++;
                                    xcol = 0;
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message + ex.StackTrace);
                }
            }
            return ds;
        }
        /// <summary>
        /// 把datagridview的修改保存到xml
        /// </summary>
        /// <param name="xmlPath"></param>
        /// <param name="dgvLockInfo"></param>
        public static bool DgvSaveAsXml(string xmlPath, DataGridView dgvLockInfo, string devIp)
        {
            bool result = false;
            XmlDocument doc = new XmlDocument();
            try
            {
                XmlElement root = doc.CreateElement("root");
                XmlElement config = doc.CreateElement("config");
                XmlElement subDevInfo = doc.CreateElement("SubDev_Info");
                int rowCount = dgvLockInfo.Rows.Count;//行数
                int colCount = dgvLockInfo.Rows[0].Cells.Count;//列数
                for (int i = 0; i < rowCount; i++)//遍历datagridview行 每行对应xml一个SubID1_Lock节点
                {
                    XmlElement subUnitInfo = doc.CreateElement("SubID" + devIp + "_Lock");
                    for (int j = 1; j < colCount; j++)//遍历列，每列对应xml一个Chl1_Lock节点
                    {
                        XmlElement chl = doc.CreateElement("Chl" + j + "_Lock");
                        chl.SetAttribute("Value", Convert.ToString(dgvLockInfo.Rows[i].Cells[j].Value));
                        subUnitInfo.AppendChild(chl);
                    }
                    subDevInfo.AppendChild(subUnitInfo);
                }
                config.AppendChild(subDevInfo);
                root.AppendChild(config);
                doc.AppendChild(root);
                doc.Save(xmlPath);
                result = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + ex.StackTrace);
            }
            return result;
        }
        /// <summary>
        /// 获取通道锁定信息
        /// </summary>
        /// <param name="filePath">xml文件路径</param>
        /// <param name="channels">通道数据类</param>
        /// <returns></returns>
        public static List<Channel> GetChlLockStat(string filePath, List<Channel> channels, string devIp)
        {
            bool lockstat = false;
            if (System.IO.File.Exists(filePath))
            {
                //导入xml文档
                XmlDocument xmlDoc = new XmlDocument();
                try
                {
                    xmlDoc.Load(filePath);//加载xml文件
                    XmlNode root = xmlDoc.SelectSingleNode("root");
                    if (root != null)//1.如果文件存在且通道不为空
                    {

                        XmlNodeList xmlNodeList = xmlDoc.GetElementsByTagName("SubID" + devIp + "_Lock");
                        XmlNodeList unitXmlNodeList = xmlNodeList[0].ChildNodes;
                        //选择SubDev_Info结点并得到旗下所有子节点
                        for (int i = 0; i < channels.Count; i++)
                        {
                            foreach (XmlNode chilnode in unitXmlNodeList)
                            {
                                string mapXmlNode = "Chl" + channels[i].Cid + "_Lock";
                                if (chilnode.Name == mapXmlNode)
                                {
                                    lockstat = chilnode.Attributes["Value"].Value == "0" ? false : true;
                                    channels[i].LockedStat = lockstat;
                                }
                            }
                        }

                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message + ex.StackTrace);
                }
            }
            return channels;
        }

    }
}
